package com.ly.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.ly.common.core.constants.Constants;
import com.ly.common.core.domain.TableDataInfo;
import com.ly.friend.domain.question.Question;
import com.ly.friend.domain.question.dto.QuestionQueryDTO;
import com.ly.friend.domain.question.es.QuestionES;
import com.ly.friend.domain.question.vo.QuestionDetailVO;
import com.ly.friend.domain.question.vo.QuestionVO;
import com.ly.friend.elasticsearch.QuestionRepository;
import com.ly.friend.manager.question.QuestionCacheManager;
import com.ly.friend.mapper.question.QuestionMapper;
import com.ly.friend.mapper.user.UserSubmitMapper;
import com.ly.friend.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private UserSubmitMapper userSubmitMapper;
    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {

//        questionRepository.count() 方法用于统计 Elasticsearch 索引中的文档总数
        //判断es中是否包含数据,包含的话count肯定大于0
        long count = questionRepository.count();
        if(count<=0){
            //es中不包含数据
            //从数据库中获取数据,同时同步给
            refreshQuestion();
        }
        //es中肯定会存在数据
//      创建排序(根据createTime降序排列)
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //创建分页对象
        Pageable pageable= PageRequest.of(questionQueryDTO.getPageNum()-1, questionQueryDTO.getPageSize(),sort);
//      获取 questionQueryDTO 中的 difficulty 和 keyword 参数
        Integer difficulty=questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();

        Page<QuestionES> questionESPage;

        if(difficulty==null&& StrUtil.isEmpty(keyword)){
            //获取所有数据
            questionESPage= questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            //根据 难度 查询数据(为空说明没有,没有就是前端没有输入)
            questionESPage=questionRepository.findQuestionByDifficulty(difficulty,pageable);
        } else if (difficulty==null) {
            //根据 标题或内容 查询数据
            questionESPage=questionRepository.findByTitleOrContent(keyword,keyword,pageable);
        }else{
            //根据标题、内容和难度查询数据
            questionESPage=questionRepository.findByTitleOrContentAndDifficulty(keyword,keyword,difficulty,pageable);
        }
        //查询总数
        long total = questionESPage.getTotalElements();
        if(total<=0){
            return TableDataInfo.empty();
        }
        //获取查询结果的内容List
        List<QuestionES> questionESList = questionESPage.getContent();
        //使用 BeanUtil.copyToList() 方法将 QuestionES 列表转换为 QuestionVO 列表，
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList,total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        //从es中查询
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO=new QuestionDetailVO();

        //如果es中存在数据,直接返回
        if(questionES!=null){
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        //如果es中不存在数据,从数据库中查询
        Question question=questionMapper.selectById(questionId);
        if(question!=null){
            return null;
        }
        //刷新缓存
        refreshQuestion();
        BeanUtil.copyProperties(questionES,questionDetailVO);
        return questionDetailVO;

    }

    @Override
    public String preQuestion(Long questionId) {
        Long index = questionCacheManager.getListSize();
        if(index==null||index<=0){
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long index = questionCacheManager.getListSize();
        if(index==null||index<=0){
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(questionId).toString();
    }

    @Override
    public List<QuestionVO> hotList() {
        Long total = questionCacheManager.getHostListSize();
        List<Long> hotQuestionIdList;
        if (total == null || total <= 0) {
            PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
            hotQuestionIdList = userSubmitMapper.selectHostQuestionList();
            questionCacheManager.refreshHotQuestionList(hotQuestionIdList);
        } else {
            hotQuestionIdList = questionCacheManager.getHostList();
        }
        return assembleQuestionVOList(hotQuestionIdList);
    }

    private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)) {
            return new ArrayList<>();
        }
        List<QuestionVO> resultList = new ArrayList<>();
        for (Long questionId : hotQuestionIdList) {
            QuestionVO questionVO = new QuestionVO();
            QuestionDetailVO detail = detail(questionId);
            questionVO.setTitle(detail.getTitle());
            resultList.add(questionVO);
        }
        return resultList;
    }

    private void refreshQuestion() {
        // 1. 从MySQL获取所有题目
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if(CollectionUtil.isEmpty(questionList)){
            return;//无数据退出
        }
        //批量保存到ES
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
}
